package com.huika.dealontop.control.login.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.support.domain.FindPwdCodeBean;
import com.huika.dealontop.support.domain.UserRegisterResult;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.LoginUtils;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.dealontop.views.cleardit.ClearableEditText;
import com.huika.dealontop.views.webview.BaseWebViewAct;
import com.huika.huikalib.utils.StringUtils;
import com.huika.huikalib.validation.EditTextValidator;


public class RegisterActivity extends BaseAct implements CompoundButton.OnCheckedChangeListener {
    private ClearableEditText etPhone;
    private ClearableEditText etVerfy;
    private ClearableEditText etPwd;
    private TextView btnVerfy;
    private Button btnRegister;


    private EditTextValidator phoneValidator;
    private EditTextValidator editTextValidator;

    private String phone;
    private String pwd;
    private TextView mSelectMail;
    private TextView mSelectPhone;
    private View mViewPhone;
    private View mViewMail;

    private ClearableEditText mRecommendation;
    private CheckBox mAgreeClause;
    private CheckBox mAgreeInformation;
    //默认是同意优惠信息的
    private int isAgreeInformation = 1;
    //默认是手机
    private int mGetPhoneMail = 1;
    private ClearableEditText mPwdAgain;
    private CountDownTimer mTimeStart;
    private TextView mDealonTopToNet;
    private TextView mInformation;


    @Override
    public void setRootView() {
        setContentView(R.layout.activity_register);
    }

    @Override
    protected void initWidget() {
        initTitle();

        mSelectMail = (TextView) findViewById(R.id.register_select_mail);
        mSelectPhone = (TextView) findViewById(R.id.register_select_phone);
        mViewPhone = findViewById(R.id.register_view_phone);
        mViewMail = findViewById(R.id.register_view_mail);
        mInformation = (TextView) findViewById(R.id.register_information);

        mRecommendation = (ClearableEditText) findViewById(R.id.register_recommendation);
        mAgreeInformation = (CheckBox) findViewById(R.id.register_agree_dealontop_information);
        mAgreeClause = (CheckBox) findViewById(R.id.register_agree_clause);
        mDealonTopToNet = (TextView) findViewById(R.id.register_DealonTopToNet);
        etPhone = (ClearableEditText) findViewById(R.id.et_phone_ar);
        etVerfy = (ClearableEditText) findViewById(R.id.et_verfy_ar);
        etPwd = (ClearableEditText) findViewById(R.id.register_pwd);
        mPwdAgain = (ClearableEditText) findViewById(R.id.register_again_pwd);
        btnVerfy = (TextView) findViewById(R.id.btn_verfy_ar);
        btnRegister = (Button) findViewById(R.id.btn_regist_ar);

        //第三条信息的addLink
        setInformation();
        //TODO
        // 验证码在没有获取的时候,无法点击
        setVerfyEt(false);
        //手机号码校验器
        //phoneValidator = new EditTextValidator(this).add(new ValidationModel(etPhone, new PhoneNumberValidation())).execute();
        // editTextValidator = new EditTextValidator(this).add(new ValidationModel(etVerfy, new VerifyNumberValidation())).add(new ValidationModel(etPwd, new PassWordValidation())).execute();
        //TODO
        //手机内容监听器 需要了解泰国的手机号码.
        etPhone.addTextChangedListener(new TextWatcher() {
                                           @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                                           @Override
                                           public void onTextChanged(CharSequence s, int start, int before, int count) {

                                           }

                                           CharSequence ms = null;

                                           @Override
                                           public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                                               ms = s;
                                           }

                                           @Override
                                           public void afterTextChanged(Editable s) {
                                               int t = ms.length();
                                               if (mGetPhoneMail == 1) {
                                                   if (t > 10) {
                                                       s.delete(t - 1, t);

                                                       etPhone.setText(s);
                                                       etPhone.setSelection(t - 1);
                                                   }
                                               }
                                           }


                                       }

        );

        etPwd.addTextChangedListener(new

                        MyPassWordWatcher(etPwd)

        );

        initListener();
    }


    private void setInformation() {
        // TextView myTextView = (TextView)findViewById(R.id.myTextView);
        String url = UIUtils.getString(R.string.register_information3);

//38bdee

        //url = "已认真阅读并同意遵守<a  href=\"http://jb51.net\">1</> ";
        String text_key = null;
        switch (UIUtils.getString(R.string.common_lang)) {
            //中文的处理方式。
            case "1":
                url = "已认真阅读并同意遵守《DealonTop网用户协议》";
                text_key = "《DealonTop网用户协议》";

                break;
            case "2":
                url = "I have carefully read and agree to abide by DealonTop User Agreement";
                text_key = "DealonTop User Agreement";
                break;
            case "3":
                url = "ฉันยอมรับข้อตกลงและเงื่อนไขการเป็นสมาชิกDealonTop";
                text_key = "ข้อตกลงและเงื่อนไข";
                break;
            default:
                break;
        }


        int startIndex = url.indexOf(text_key);
        int endIndex = startIndex + text_key.length();

        SpannableStringBuilder builder = new SpannableStringBuilder(url);

    //可单独文本前景色
		builder.setSpan(new ForegroundColorSpan(UIUtils.getColor(R.color.color_38bdee)), startIndex,
				endIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        //设置文本点击事件
        builder.setSpan(new ClickSpannable(this), startIndex, endIndex,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


        mDealonTopToNet.setMovementMethod(LinkMovementMethod.getInstance());
        mDealonTopToNet.setText(builder);


        //mDealonTopToNet.setText(Html.fromHtml(url));


    }


    /**
     * SpannableStringBuilder 点击事件
     */
    private class ClickSpannable extends ClickableSpan implements
            View.OnClickListener {

        private View.OnClickListener onClickListener;

        public ClickSpannable(View.OnClickListener onClickListener) {
            this.onClickListener = onClickListener;
        }

        @Override
        public void onClick(View widget) {
            onClickListener.onClick(widget);
            //showToastMsg("我被点击了。");
        }
    }


    private void initTitle() {
        TitleBarHelper titleBarHelper = new TitleBarHelper(this, -1, -1, R.string.title_register);
        //titleBarHelper.setRightMsg(R.string.left_cancle);
        titleBarHelper.setOnLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aty.finish();
            }
        });
    }

    private void initListener() {
        mAgreeInformation.setOnCheckedChangeListener(this);
        mSelectMail.setOnClickListener(this);
        mSelectPhone.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        btnVerfy.setOnClickListener(this);
        // mDealonTopToNet.setOnClickListener(this);

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {


            case R.id.register_agree_dealontop_information:

                if (mAgreeInformation.isChecked()) {
                    isAgreeInformation = 1;
                } else {
                    isAgreeInformation = 0;
                }

                break;
            case R.id.register_agree_clause:

                break;

            default:
                break;
        }
    }

    class MyPassWordWatcher implements TextWatcher {
        private EditText editText;
        private String tempStr;

        public MyPassWordWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (tempStr.indexOf(" ") != -1) {
                editText.setText(tempStr.trim());
                editText.setSelection(tempStr.length());
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().equals(" ")) {
                editText.setText("");
            } else {
                tempStr = s.toString();
            }
        }

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {
            case R.id.register_DealonTopToNet:
                Intent intent = new Intent(this, BaseWebViewAct.class);

                switch (UIUtils.getString(R.string.common_lang)) {
                    case "1":
                        intent.putExtra(BaseWebViewAct.PAGE_URL, UrlConstants.DEALONTOPURL);
                        break;
                    case "2":
                        intent.putExtra(BaseWebViewAct.PAGE_URL, UrlConstants.DEALONTOPURLEN);
                        break;
                    case "3":
                        intent.putExtra(BaseWebViewAct.PAGE_URL, UrlConstants.DEALONTOPURLTH);
                        break;
                }
                intent.putExtra(BaseWebViewAct.PAGE_TITLE, "DealonTop");
                startActivity(intent);
                break;
            case R.id.btn_verfy_ar:
                verfyNet();
                break;
            case R.id.btn_regist_ar:
                register();
                break;
            case R.id.register_select_phone:
                //1是手機
                mGetPhoneMail = 1;
                selectPhone();
                etPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
                break;
            case R.id.register_select_mail:
                //2是郵箱
                mGetPhoneMail = 2;
                selectMail();
                etPhone.setInputType(InputType.TYPE_CLASS_TEXT);
                break;

            default:
                break;
        }
    }

    private void selectMail() {
        mInformation.setText(UIUtils.getString(R.string.register_information));
        //
        mSelectMail.setTextColor(getResources().getColor(R.color.color_fd702b));
        mViewMail.setBackgroundResource(R.mipmap.register_line_yellow_xian);
        //
        mSelectPhone.setTextColor(Color.BLACK);
        mViewPhone.setBackgroundResource(R.mipmap.register_line_white_xian);
        etPhone.setHint(getResources().getString(R.string.register_e_mail));
        //选了邮箱将手机号码清空
        etPhone.setText("");
        mRecommendation.setText("");
        etVerfy.setText("");
        etPwd.setText("");
        mPwdAgain.setText("");
        if (mTimeStart != null) {
            mTimeStart.cancel();
            mTimeStart.onFinish();
        }
    }


    private void selectPhone() {

        mSelectPhone.setTextColor(getResources().getColor(R.color.color_fd702b));
        mViewPhone.setBackgroundResource(R.mipmap.register_line_yellow_xian);
        //
        mSelectMail.setTextColor(Color.BLACK);
        mViewMail.setBackgroundResource(R.mipmap.register_line_white_xian);

        mInformation.setText(UIUtils.getString(R.string.register_information_phone));
        etPhone.setHint(getResources().getString(R.string.register_thailand_phonenumber));
        etPhone.setText("");
        mRecommendation.setText("");
        etVerfy.setText("");
        etPwd.setText("");
        mPwdAgain.setText("");


        if (mTimeStart != null) {
            mTimeStart.cancel();
            mTimeStart.onFinish();
        }

    }

    private boolean isPhoneMail() {
        String tempStr = UIUtils.getString(R.string.register_thailand_phonenumber);
        if (tempStr.equals(etPhone.getHint())) {
            return true;
        }
        return false;
    }

    private boolean performIllegal() {
        phone = getInputStr(etPhone);
        if (isPhoneMail()) {
            if (StringUtils.isEmpty(phone)) {
                showToastMsg(getString(R.string.register_illegalemptyphone));
                return false;
            }
            if (!StringUtils.isTaiPhone(phone)) {
                showToastMsg(getString(R.string.register_illegalphone));
                return false;
            }
        } else {
            if (StringUtils.isEmpty(phone)) {
                showToastMsg(getString(R.string.register_illegalemptyemail));
                return false;
            }
            if (!StringUtils.isEmail(phone)) {
                showToastMsg(getString(R.string.register_illegalemail));
                return false;
            }
        }
        return true;
    }

    private void verfyNet() {
        if (!performIllegal()) {
            return;
        }
        ;
        showLoadingDialog("");
        phone = getInputStr(etPhone);
        //获取验证码
        FormResultRequest request = new FormResultRequest(UrlConstants.GETSMSVERIFICATION, codeListener, this, new TypeToken<RequestResult<FindPwdCodeBean>>() {
        }.getType());
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();

        ajaxParams.putStringTypeParam("account", phone);
        //账号类型（1.手机号码 2.电子邮箱）
        ajaxParams.putCommonTypeParam("accType", mGetPhoneMail);
        //类型（注册1,找回密码2,修改密码3,优惠券4,商家审核短信下发5,快速登录6,订阅手机发送7,修改手机8,完善资料（邮箱注册添加手机号）9,修改邮箱10）
        ajaxParams.putCommonTypeParam("type", Constants.ValidateType.REGISTER);

        ajaxParams.putCommonTypeParam("registerSource", Constants.RegisterSource.ANDROID);

        //ajaxParams.putStringTypeParam("lang", UIUtils.getString(R.string.common_lang));

        request.setRequestParams(ajaxParams);
        executeRequest(request);
        // }
    }

    private void register() {

        if (!performIllegal()) {
            return;
        }
        ;

        if (TextUtils.isEmpty(etVerfy.getText())) {
            showToastMsg(getString(R.string.register_empty_verfy));
            return;
        }

        if (TextUtils.isEmpty(etPwd.getText()) || TextUtils.isEmpty(mPwdAgain.getText())) {
            showToastMsg(getString(R.string.register_empty_password));
            return;
        } else if (!etPwd.getText().toString().equals(mPwdAgain.getText().toString())) {
            showToastMsg(getString(R.string.register_empty_password_again));
            return;
        }

        if (!mAgreeClause.isChecked()) {
            showToastMsg(getString(R.string.register_agree_clause));
            return;
        }


        pwd = getInputStr(etPwd);
        //判断密码为6-16位数组成

        int tempLength = pwd.toString().trim().toCharArray().length;
        if (tempLength > 16 || tempLength < 6) {
            showToastMsg(getString(R.string.register_password_number));
            return;
        }

        showLoadingDialog("");

        FormResultRequest<UserRegisterResult> request = new FormResultRequest<UserRegisterResult>(UrlConstants.REGISTER, registerListener, this, new TypeToken<RequestResult<UserRegisterResult>>() {
        }.getType());
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        //账号（RSA加密）"0888123456"
        ajaxParams.putStringTypeParam("account", phone);
        //密码（MD5+RSA加密）
        ajaxParams.putStringTypeParam("passWord", MD5Security.getMd5_32_UP(pwd));
        //验证码
        ajaxParams.putStringTypeParam("validate", getInputStr(etVerfy));
        //1-网站 2-android 3-ios
        ajaxParams.putCommonTypeParam("registerSource", Constants.RegisterSource.ANDROID);
        //类型（1.手机号码，2.邮箱地址）
        ajaxParams.putCommonTypeParam("type", mGetPhoneMail);

        if (!TextUtils.isEmpty(mRecommendation.getText())) {
            //推荐码
            ajaxParams.putStringTypeParam("referralCode", mRecommendation.getText() + "");
        }

        //是否同意订阅Dealontop的优惠信息(0 不同意 1 同意)
        ajaxParams.putCommonTypeParam("boolSubscibe", isAgreeInformation);
//        //1：中文，2：英文,3:泰文
//        ajaxParams.putCommonTypeParam("lang", UIUtils.getString(R.string.common_lang));

        request.setRequestParams(ajaxParams);
        executeRequest(request);
        //}
    }

    private Response.Listener<RequestResult<FindPwdCodeBean>> codeListener = new Response.Listener<RequestResult<FindPwdCodeBean>>() {
        @Override
        public void onResponse(RequestResult<FindPwdCodeBean> arg0) {
            dismissLoadingDialog();
            showToastMsg(arg0.msg);
            btnVerfy.setClickable(false);
            setVerfyEt(true);
            mTimeStart = new CountDownTimer(120000, 1000) {
                public void onTick(long millisUntilFinished) {
                    //btnVerfy.setTextColor(getResources().getColor(R.color.color_969696));
                    btnVerfy.setText(String.format("%s" + "S", String.valueOf(millisUntilFinished / 1000)));

                }

                public void onFinish() {
                    //btnVerfy.setTextColor(getResources().getColor(R.color.color_f25522));
                    btnVerfy.setText(R.string.register_getVerification);
                    btnVerfy.setClickable(true);
                }
            }.start();

        }
    };

    private Response.Listener<RequestResult<UserRegisterResult>> registerListener = new Response.Listener<RequestResult<UserRegisterResult>>() {
        @Override
        public void onResponse(RequestResult<UserRegisterResult> arg0) {
            dismissLoadingDialog();
            if (arg0.flag == 1) {
                LoginUtils loginUtils = new LoginUtils(RegisterActivity.this);
                loginUtils.login(phone, pwd);
                //aty.finish();
                UserRegisterResult rs = arg0.getRs();
                //类型（1.手机号码，2.邮箱地址）
                if (mGetPhoneMail == Constants.AccountType.PHONE) {

                    Intent intent = new Intent(aty, SuccessPageOne.class);
                    intent.putExtra("SuccessTwo", rs.getIsRecommend());
                    skipActivity(aty, intent);
                } else if (mGetPhoneMail == Constants.AccountType.EMAIL) {
                    Intent intent = new Intent(aty, SuccessPageTwo.class);
                    intent.putExtra("SuccessTwo", rs.getIsRecommend());
                    skipActivity(aty, intent);
                }


            }
            //注册成功,然后会进入另一个窗口,不会弹吐司了.
            showToastMsg(arg0.msg);

        }
    };

    private void setVerfyEt(boolean isShow) {
        if (isShow) {
            etVerfy.setEnabled(true);
        } else {
            etVerfy.setEnabled(false);
        }
    }

}
